<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/10/14
 * Time: 10:32
 */

namespace app\api\controller;


use language\Languagemsg;
use pay\Paypal;
use pay\Upacp;
use think\Db;
use pay\Ali;
use pay\Wx;

class Goodsorder extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->msg_language = new Languagemsg();
        $this->language = input('language') ? input('language') : 0;
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301, 'msg'=>$this->msg_language->otherLogin[$this->language]]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->msg_language->frost[$this->language]]);
            exit;
        }
    }
    
    /**
     * 订单列表
     * @return \think\response\Json
     * order_status   订单状态  0 全部  1 待付款  2 待发货  3 待收货  4 待评价  8 已关闭   -1 售后（5 售后中  6 售后完成/已退款  7 拒绝退款）
     * from_type      请求来源  1 “我的”页面   2 店铺订单管理   3 今日订单
     */
    public function orderList(){
        // 订单状态  0 全部  1 待付款  2 待发货  3 待收货  4 待评价  8 已关闭  -1 售后（5 售后中  6 售后完成/已退款  7 拒绝退款）
        $order_status = input('order_status');
        $from_type = input('from_type'); // 1 “我的”页面   2 店铺订单管理  3 今日订单
        if($from_type == 3){
            $date = date('Y-m-d');
            $list = $this->order($order_status, 1, $from_type, $date);
        }else{
            $list = $this->order($order_status, 1, $from_type);
        }
        
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 订单详情
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $order = Db::table('up_goods_order')
            ->join('up_goods', 'goods_id = order_goods_id', 'LEFT')
            ->join('up_shop', 'order_sail_user_id = shop_user_id', 'LEFT')
            ->join('up_goods_spec', 'order_spec_id = spec_id', 'LEFT')
            ->join('up_u_user uuu1', 'uuu1.user_id = order_buy_user_id', 'LEFT')
            ->join('up_u_user uuu2', 'uuu2.user_id = order_sail_user_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_id, shop_user_id, shop_name, goods_id, goods_thumb, goods_name, spec_name, 
            spec_price, spec_old_price, spec_can, order_num, order_goods_price, order_coupon_price, 
            order_pay_price, order_number, order_type, order_status, order_liuyan, order_wuliu_code, order_wuliu_name, 
            order_create_time, order_pay_time, order_pay_type, order_send_time, order_over_time, order_comment_time, 
            order_aftersale_time, order_addr_id, shop_id, order_buy_user_id, order_aftersale_status, order_do_aftersale_time, 
            uuu2.user_username sale_username, uuu2.user_image sale_user_image, order_yue_id')
            ->find();
        $sale_reason = Db::table('up_aftersail')
            ->join('up_aftersail_reason', 'ar_id = as_reason_id', 'LEFT')
            ->where('as_order_id', $order['order_id'])
            ->field('ar_name, as_desc, as_image')
            ->find();
        if($sale_reason){
            // 售后图片
            if($sale_reason['as_image']){
                $image = trim($sale_reason['as_image'], ',');
                $order['aftersale_image'] = explode(',', $image);
            }else{
                $order['aftersale_image'] = [];
            }
            $order['aftersale_reason'] = $sale_reason['ar_name']; // 售后原因
            $order['aftersale_desc'] = $sale_reason['as_desc']; // 售后描述
        }else{
            $order['aftersale_image'] = []; // 售后图片
            $order['aftersale_reason'] = ''; // 售后原因
            $order['aftersale_desc'] = ''; // 售后描述
        }
            
        $order['address'] = $this->getAddress($order['order_addr_id']);
        return json(['status' => 200, 'msg' => $order, 'now' => time()]);
    }
    
    /**
     * 买家取消订单
     * 修改订单状态、释放库存
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function cancelOrder(){
        $order_id = input('order_id');
        $order = $this->orderInfo($order_id);
        Db::startTrans();
        try{
            //  修改订单状态
            Db::table('up_goods_order')->where('order_id', $order_id)->update(['order_status' => 8, 'order_canecl_time' => $this->create_time]);
            // 释放库存
            Db::table('up_goods_spec')->where('spec_id', $order['order_spec_id'])->setInc('spec_stock', $order['order_num']);
            Db::commit();
//            return json(['status' => 200, 'msg' => '操作成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->doSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 确认订单
     * 修改订单状态、增加商品销量
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function overOrder(){
        $order_id = input('order_id');
        $order = $this->orderInfo($order_id);
        Db::startTrans();
        try{
            Db::table('up_goods_order')
                ->where('order_id', $order_id)
                ->update([
                    'order_status' => 4,
                    'order_over_time' => $this->create_time
                ]);
            // 约稿订单，同步约稿状态
            if($order['order_type'] == 4){
                Db::table('up_yue')->where('yue_id', $order['order_yue_id'])->setField('yue_status', 5);
            }else{
                // 增加商品、规格销量
                Db::table('up_goods')->where('goods_id', $order['order_goods_id'])->setInc('goods_sail_num', $order['order_num']);
                Db::table('up_goods_spec')->where('spec_id', $order['order_spec_id'])->setInc('spec_sail_num', $order['order_num']);
            }
            
            Db::commit();
//            return json(['status' => 200, 'msg' => '操作成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->doSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 售后类型
     * @return \think\response\Json
     */
    public function aftersaleType(){
        $type = Db::table('up_aftersail_reason')
            ->where('ar_status', 1)
            ->field('ar_id, ar_name')
            ->order('ar_time desc')
            ->select();
        if($type){
            return json(['status' => 200, 'msg' => $type]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 提交售后
     * @return \think\response\Json
     * order_id      订单ID
     * as_reason_id  售后原因ID
     * as_desc       售后描述
     * as_image      图片
     * as_phone      手机号
     */
    public function afterSale(){
        $as_reason_id = input('as_reason_id');
        $order_id = input('order_id');
        $as_desc = input('as_desc');
        $as_image = input('as_image');
        $as_phone = input('as_phone');
        $order = $this->orderInfo($order_id);
        $insert = [
            'as_reason_id' => $as_reason_id,
            'as_order_id' => $order_id,
            'as_goods_id' => $order['order_goods_id'],
            'as_spec_id' => $order['order_spec_id'],
            'as_user_id' => $this->user_id,
            'as_desc' => $as_desc,
            'as_image' => $as_image,
            'as_phone' => $as_phone,
            'as_time' => $this->create_time
        ];
        Db::startTrans();
        try{
            Db::table('up_aftersail')->insert($insert);
            Db::table('up_goods_order')
                ->where('order_id', $order_id)
                ->update(['order_status' => 5, 'order_aftersale_time' => $insert['as_time']]);
            Db::commit();
//            return json(['status' => 200, 'msg' => '提交成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->commitSuccess[$this->language], 'time' => $insert['as_time']]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 评价订单时的商品展示
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function orderGoods(){
        $order_id = input('order_id');
        $goods = Db::table('up_goods_order')
            ->join('up_goods', 'goods_id = order_goods_id', 'LEFT')
            ->join('up_goods_spec', 'spec_id = order_spec_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('goods_name, goods_thumb, spec_name, spec_can')
            ->find();
        return json(['status' => 200, 'msg' => $goods]);
    }
    
    /**
     * 评价订单
     * @return \think\response\Json
     * order_id       订单ID
     * gc_star        星级   1 1星   2 2星   3 3星   4 4星   5 5星
     * gc_content     评价内容
     * gc_images      评价图片
     */
    public function commentOrder(){
        $order_id = input('order_id');
        $gc_star = input('gc_star');
        $gc_content = input('gc_content');
        $gc_images = input('gc_images');
        $order = $this->orderInfo($order_id);
        Db::startTrans();
        try{
            // 订单状态
            Db::table('up_goods_order')
                ->where('order_id', $order_id)
                ->update([
                    'order_status' => 9,
                    'order_comment_time' => $this->create_time
                ]);
            // 评论表
            $insert = [
                'gc_goods_id' => $order['order_goods_id'],
                'gc_spec_id' => $order['order_spec_id'],
                'gc_user_id' => $this->user_id,
                'gc_order_id' => $order_id,
                'gc_star' => $gc_star,
                'gc_content' => $gc_content,
                'gc_images' => $gc_images,
                'gc_time' => $this->create_time
            ];
            
            if($gc_star >= 3){ // 好评
                $insert['gc_type'] = 1;
                // 好评+1
                Db::table('up_goods')->where('goods_id', $order['order_goods_id'])->setInc('goods_high');
            }else{
                $insert['gc_type'] = 2;
            }
            Db::table('up_goods_comment')->insert($insert);
            // 评论数量+1
            Db::table('up_goods')->where('goods_id', $order['order_goods_id'])->setInc('goods_comment_num');
            Db::commit();
//            return json(['status' => 200, 'msg' => '评论成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->commentSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 我的评价
     * @return \think\response\Json
     * page    页码
     */
    public function myOrderComment(){
        $comment = Db::table('up_goods_comment')
            ->join('up_u_user', 'user_id = gc_user_id', 'LEFT')
            ->join('up_goods_spec', 'gc_spec_id = spec_id', 'LEFT')
            ->where('gc_user_id', $this->user_id)
            ->field('user_username, user_image, gc_star, gc_time, spec_name, spec_can, gc_content, 
            gc_images')
            ->page($this->page, 15)
            ->order('gc_time desc')
            ->select();
        if($comment){
            foreach($comment as $k => $v){
                if($v['gc_images']){
                    $images = trim($v['gc_images'], ',');
                    $comment[$k]['gc_images'] = explode(',', $images);
                }else{
                    $comment[$k]['gc_images'] = [];
                }
            }
            return json(['status' => 200, 'msg' => $comment]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 取消售后
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function cancelAftersale(){
        $order_id = input('order_id');
        Db::startTrans();
        try{
            // 删除售后表中的记录
            Db::table('up_aftersail')->where('as_order_id', $order_id)->delete();
            // 修改订单状态,要根据是否评价过，恢复到原来状态
            $is_comment = Db::table('up_goods_comment')->where('gc_order_id', $order_id)->find();
            if($is_comment){ // 如果已经评价过，就恢复到已评价状态
                Db::table('up_goods_order')->where('order_id', $order_id)->setField('order_status', 9);
            }else{ // 如果没有评价过，就恢复到已确认收货状态
                Db::table('up_goods_order')->where('order_id', $order_id)->setField('order_status', 4);
            }
            Db::commit();
//            return json(['status' => 200, 'msg' => '操作成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->doSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 删除订单
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function delOrder(){
        $order_id = input('order_id');
        $res = Db::table('up_goods_order')->where('order_id', $order_id)->setField('order_del', 2);
        if($res){
//            return json(['status' => 200, 'msg' => '删除成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->delSuccess[$this->language]]);
        }else{
//            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            return json(['status' => 0, 'msg' => $this->msg_language->systemErr[$this->language]]);
        }
    }
    
    /**
     * 发货
     * @return \think\response\Json
     * order_id            订单ID
     * order_wuliu_code    快递单号
     * order_wuliu_name    快递公司
     */
    public function sendGoods(){
        $order_id = input('order_id');
        $order_wuliu_code = input('order_wuliu_code');
        $order_wuliu_name = input('order_wuliu_name');
        $order = $this->orderInfo($order_id);
        $update = [
            'order_wuliu_code' => $order_wuliu_code,
            'order_wuliu_name' => $order_wuliu_name,
            'order_status' => 3,
            'order_send_time' => $this->create_time
        ];
        Db::startTrans();
        try{
            // 订单状态
            Db::table('up_goods_order')->where('order_id', $order_id)->update($update);
            // 约稿订单，同步约稿状态
            if($order['order_type'] == 4){
                Db::table('up_yue')->where('yue_id', $order['order_yue_id'])->setField('yue_status', 3);
            }
            Db::commit();
//            return json(['status' => 200, 'msg' => '操作成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->doSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 拒绝售后
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function refuseAftersale(){
        $order_id = input('order_id');
        $res = Db::table('up_goods_order')
            ->where('order_id', $order_id)
            ->update([
                'order_status' => 7,
                'order_do_aftersale_time' => $this->create_time
            ]);
        if($res){
//            return json(['status' => 200, 'msg' => '操作成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->doSuccess[$this->language]]);
        }else{
//            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            return json(['status' => 0, 'msg' => $this->msg_language->systemErr[$this->language]]);
        }
    }
    
    /**
     * 根据收货地址ID，获取收货地址信息
     * @return \think\response\Json
     * addr_id      收货地址ID
     */
    public function getAddressById(){
        $addr_id = input('addr_id');
        $address = $this->getAddress($addr_id);
        if($address){
            return json(['status' => 200, 'msg' => $address]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
        
    }
    
    /**
     * 展示快递单号
     * @return \think\response\Json
     */
    public function showWL(){
        $order_id = input('order_id');
        $wuliu = Db::table('up_goods_order')
            ->where('order_id', $order_id)
            ->field('order_wuliu_name, order_wuliu_code')
            ->find();
        return json(['status' => 200, 'msg' => $wuliu]);
    }
    
    /**
     * 卖家同意退款
     * @return \think\response\Json
     * order_id      订单ID
     */
    public function agreeAftersale(){
        $order_id = input('order_id');
        // TODO:先退款，然后改变订单状态，释放库存，修改销量
        $order = Db::table('up_goods_order')
            ->where('order_id', $order_id)
            ->field('order_number, order_pay_type, order_num, order_type, order_spec_id, 
            order_goods_id, order_pay_price, order_USD_price, order_return_number')
            ->find();
        // TODO:其他类型退款
        // 退款订单号，银联和微信退款需重新生成一个不同于消费时的订单号
        $return_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($order['order_pay_type'] == 1){ // 微信
            import('returnprice.Wx', EXTEND_PATH);
            $wx = new Wx(config('weixin'));
            $return = $wx->weixiReturn($order['order_pay_price'], $order['order_pay_price'], $order['order_number'], $return_number);
        }elseif($order['order_pay_type'] == 2){ // 支付宝
            import('returnprice.Ali', EXTEND_PATH);
            $ali = new Ali(config('ali'));
            $return = $ali->aliReturn($order['order_pay_price'], $order['order_number']);
        }elseif($order['order_pay_type'] == 3){ // 银联
            import('returnprice.Upacp', EXTEND_PATH);
            $upacp = new Upacp();
            $return = $upacp->yinLianRefund($return_number, $order['order_return_number'], $order['order_pay_price']);
        }elseif($order['order_pay_type'] == 4){ // visa
        
        }else{ // PayPal
            import('returnprice.Paypal', EXTEND_PATH);
            $payPal = new Paypal();
            $return = $payPal->returnPrice($order['order_USD_price'], $order['order_return_number']);
        }
        
        if($return['status'] == 200){
            Db::startTrans();
            try{
                // 修改订单状态
                $update = [
                    'order_status' => 6,
                    'order_do_aftersale_time' => $this->create_time
                ];
                if($order['order_pay_type'] == 1){
                    $update['order_return_number'] = $return_number;
                }
                if($order['order_pay_type'] == 3){
                    $update['order_upacp_return_number'] = $return_number;
                }
                Db::table('up_goods_order')
                    ->where('order_id', $order_id)
                    ->update($update);
                // 正常商品、秒杀商品、拍卖商品，释放库存、减销量
                if($order['order_type'] == 1 || $order['order_type'] == 2 || $order['order_type'] == 3){
                    // 释放库存
                    Db::table('up_goods_spec')->where('spec_id', $order['order_spec_id'])->setInc('spec_stock', $order['order_num']);
                    // 减销量
                    $spec = Db::table('up_goods_spec')->where('spec_id', $order['order_spec_id'])->field('spec_sail_num')->find();
                    if($spec['spec_sail_num'] > 0){
                        Db::table('up_goods_spec')->where('spec_id', $order['order_spec_id'])->setDec('spec_sail_num', $order['order_num']);
                    }
                    $goods = Db::table('up_goods')->where('goods_id', $order['order_goods_id'])->field('goods_sail_num')->find();
                    if($goods['goods_sail_num'] > 0){
                        Db::table('up_goods')->where('goods_id', $order['order_goods_id'])->setDec('goods_sail_num', $order['order_num']);
                    }
                }
                Db::commit();
                return json(['status' => 200, 'msg' => '操作成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 0, 'msg' => $return['msg']]);
        }
    }
    
    /**
     * 收货地址
     * @param $addr_id   收货地址ID ，如果为0，则取用户默认收货地址
     * @return array|false|\PDOStatement|string|\think\Model
     */
    private function getAddress($addr_id){
        if($addr_id == 0){
            $where['addr_user_id'] = $this->user_id;
            $where['addr_is_default'] = 1;
        }else{
            $where['addr_id'] = $addr_id;
        }
        $address = Db::table('up_user_address')
            ->join('up_area ua1', 'ua1.district_id = addr_sheng', 'LEFT')
            ->join('up_area ua2', 'ua2.district_id = addr_shi', 'LEFT')
            ->join('up_area ua3', 'ua3.district_id = addr_qu', 'LEFT')
            ->field('addr_id, addr_name, addr_phone, ua1.district sheng_name, ua2.district shi_name, 
            ua3.district qu_name, addr_address')
            ->where($where)
            ->find();
        return $address;
    }
    
    /**
     * 订单
     * @param $order_status    订单状态
     *   0 全部   1 待付款  2 待发货  3 待收货  4 待评价  8 已关闭  -1 售后（5 售后中  6 售后完成/已退款  7 拒绝退款）
     * @param $data_type       数据类型   1 列表   2 统计
     * @param $from_type       来源       1 “我的”页面    2 店铺订单管理   3 今日订单
     * @param $date            今日订单    订单日期   店铺管理，今日订单传日期，其他不传
     * @return int|string
     */
    private function order($order_status, $data_type, $from_type, $date = ''){
        $where['order_del'] = 1;
        $where['order_type'] = ['IN', '1,2,3,4'];
        if(!empty($date)) $where['order_pay_date'] = $date;
        if($from_type == 1){ // “我的”页面订单
            $where['order_buy_user_id'] = $this->user_id;
        }else{ // 店铺管理订单
            $where['order_sail_user_id'] = $this->user_id;
        }
        if($order_status != 0){
            if($order_status == -1){ // 售后状态
                $where['order_status'] = ['IN', '5,6,7'];
            }else{
                $where['order_status'] = $order_status;
            }
        }
        $order = Db::table('up_goods_order')
            ->join('up_goods', 'order_goods_id = goods_id', 'LEFT')
            ->join('up_u_user uuu1', 'uuu1.user_id = order_buy_user_id', 'LEFT')
            ->join('up_u_user uuu2', 'uuu2.user_id = order_sail_user_id', 'LEFT')
            ->join('up_goods_spec', 'spec_id = order_spec_id', 'LEFT');
        if($from_type == 1){
            $order->join('up_shop', 'shop_user_id = order_sail_user_id', 'LEFT')
                ->field('shop_id, order_status, goods_thumb, goods_name, spec_name, order_num, spec_price, spec_old_price, 
                order_pay_price, order_id, order_type, shop_name, spec_can, order_aftersale_status, uuu2.user_username sale_username, 
                uuu2.user_image sale_user_image');
        }else{
            $order->field('order_id, uuu1.user_username, uuu1.user_phone, order_number, order_type, order_status, 
                goods_thumb, goods_name, spec_name, order_num, spec_price, spec_old_price, order_pay_price, 
                order_aftersale_status, spec_can, uuu2.user_image sale_user_image, uuu2.user_username sale_username');
        }
        if($data_type == 1){ // 列表
            $order = $order->where($where)
                ->order('order_create_time desc')
                ->page($this->page, 15)
                ->select();
        }else{ // 统计
            $order = $order->where($where)->count();
        }
        return $order;
    }
    
    /**
     * 订单详情信息
     * @param $order_id    订单ID
     * @return array|false|\PDOStatement|string|\think\Model
     */
    private function orderInfo($order_id){
        $order = Db::table('up_goods_order')
            ->where('order_id', $order_id)
            ->field('order_spec_id, order_goods_id, order_num, order_pay_price, order_number, 
            order_pay_type, order_type, order_yue_id')
            ->find();
        return $order;
    }
}